package redis

import (
	"strconv"
	"time"
	"web-app/models"

	"github.com/go-redis/redis"
)

func GetPostIDsInOrder(p *models.ParamPostList) ([]string, error) {
	//从redis获取id
	key := KeyPostTimeZSet
	if p.Order == models.OrderScore {
		key = KeyPostScoreZSet
	}
	start := (p.Page - 1) * p.Size
	end := start + p.Size - 1
	return Client.ZRevRange(key, start, end).Result()
}

// 根据ids查询每篇帖子的赞成票
func GetPostvotedData(ids []string) (data []int64, err error) {
	// data =make([]int64,0,len(ids))
	// for _,id:=range ids{
	// 	//查找key中分数是1的元素的数量
	// 	V1:=Client.ZCount(KeyPostVotedZSetPre+id,"1","1").Val()
	// 	data = append(data, V1)
	// }

	//使用pipeplene一次发送多条命令
	pipeline := Client.Pipeline()
	for _, id := range ids {
		pipeline.ZCount(KeyPostVotedZSetPre+id, "1", "1")
	}
	cmders, err := pipeline.Exec()
	if err != nil {
		return nil, err
	}
	data = make([]int64, 0, len(ids))
	for _, cmder := range cmders {
		v := cmder.(*redis.IntCmd).Val()
		data = append(data, v)
	}
	return
}

func GetCommunityPostIDsInOrder(p *models.ParamPostList)([]string,error){
	//使用zinterstore 把分区的帖子set与帖子分数的zset生成一个新的zset
	//针对新的zset按之前的逻辑取数据
	//利用缓存key减少zinterstore执行次数
	orderKey:=KeyPostTimeZSet
	if p.Order == models.OrderScore {
		orderKey = KeyPostScoreZSet
	}
	cKey:=KeyCommunitySetPre+strconv.Itoa(int(p.CommunityID))
	key := orderKey+strconv.Itoa(int(p.CommunityID))
	if Client.Exists(key).Val()<1{
		pipeline:=Client.Pipeline()
		pipeline.ZInterStore(key,redis.ZStore{
			Aggregate: "MAX",
		},cKey,orderKey)//zinterstore 计算
		pipeline.Expire(key,60*time.Second)
		_,err:=pipeline.Exec()
		if err!=nil{
			return nil,err
		}
	}
	start := (p.Page - 1) * p.Size
	end := start + p.Size - 1
	return Client.ZRevRange(key, start, end).Result()
}
